package com.village.friend.sms;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.village.friend.constant.MsgCodeEnum;
import com.village.friend.dto.response.BaseResponse;
import com.village.friend.exception.AppRuntimeException;
import com.village.friend.redis.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

/**
 * 未来无线的短信发送接口
 *
 * https://wlwx.com/
 */

@Service
@Slf4j
public class WlwxSmsService implements SmsBaseService{

    @Autowired
    RedisService redisService;

    @Value("${sms.namebase64}")
    private String agentSmsNameBase64;

    private String agentSmsName;

    @Value("${wlwx.cust_code}")
    private String cust_code;
    @Value("${wlwx.cust_pwd}")
    private String cust_pwd;

    public String post(String uri, String params) throws Exception{
        URL url = new URL(uri);
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.setRequestMethod("POST");
        httpURLConnection.setDoOutput(true);
        httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        OutputStream out = httpURLConnection.getOutputStream();
        out.write(params.getBytes(StandardCharsets.UTF_8));
        log.info("发送请求 路径:\t" + uri + "\n参数:\t" + params);
        InputStream inputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader reader = null;
        StringBuffer resultBuffer = new StringBuffer();
        String tempLine = null;
        try {
            inputStream = httpURLConnection.getInputStream();
            inputStreamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
            reader = new BufferedReader(inputStreamReader);
            while ((tempLine = reader.readLine()) != null) {
                resultBuffer.append(tempLine);
            }
            log.info("返回结果 路径:\t" + uri + "\n 数据:\t" + resultBuffer.toString());

        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            if (reader != null) {
                reader.close();
            }
            if (inputStreamReader != null) {
                inputStreamReader.close();
            }
            if (inputStream != null) {
                inputStream.close();
            }
            httpURLConnection.disconnect();
        }
        return resultBuffer.toString();
    }

    private JSONObject getTokinParams() throws Exception{
        //获取token
        String tokenResult = getToken();
        JSONObject resultObject = JSONObject.parseObject(tokenResult);
        String token_id = resultObject.getString("token_id");
        String sign = resultObject.getString("token") + cust_pwd;
        sign = MD5.getMD5(sign.getBytes(StandardCharsets.UTF_8));

        //获取状态报告
        JSONObject paramsJson = new JSONObject();
        paramsJson.put("token_id",token_id);
        paramsJson.put("cust_code", cust_code);
        paramsJson.put("sign", sign);
        return paramsJson;
    }

    /**
     * 获取上行短信
     *
     * @return
     */
    public String getSms(){
        String url_getmo = "https://smsapp.wlwx.com/getMO";
        try {
            JSONObject tokinParams = getTokinParams();
            return post(url_getmo,tokinParams.toJSONString());
        }catch (Exception e){
            e.printStackTrace();
            return SmsResultBean.failtString(e.getMessage());
        }
    }


    /**
     * 获取token
     * @return
     * @throws Exception
     */
    public String getToken() throws Exception{

        String url_getToken = "https://smsapp.wlwx.com/getToken";
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("cust_code", cust_code);
        String json_getToken = jsonObject.toJSONString();
        return post(url_getToken, json_getToken);
    }

    /**
     * 获取状态报告
     * @return
     * @throws Exception
     */
    public String getReport(){
        String url_getReport = "https://smsapp.wlwx.com/getReport";

        try {
            //获取状态报告
            JSONObject paramsJson = getTokinParams();
            return post(url_getReport,paramsJson.toJSONString());
        }catch (Exception e){
            e.printStackTrace();
            return SmsResultBean.failtString(e.getMessage());
        }


    }

    /**
     * 发送短信验证码
     * @param phones
     * @param content
     * @return
     * @throws Exception
     */
    public String sendCommSms(String phones, String content) throws Exception {
        // 发送短信地址，以下为示例地址，具体地址询问网关获取
        String url_send_sms = "https://smsapp.wlwx.com/sendSms";
        // 接收号码，必填，同时发送给多个号码时,号码之间用英文半角逗号分隔
        String destMobiles = phones;
        // 业务标识，选填，由客户自行填写不超过20位的数字
        String uid = "";
        // 长号码，选填
        String sp_code = "";
        // 是否需要状态报告
        String need_report = "yes";
        // 数字签名，签名内容根据 “短信内容+客户密码”进行MD5编码后获得
        content = "【" + getAgentSmsName() + "】" + content;
        String sign = content + cust_pwd;
        sign = MD5.getMD5(sign.getBytes(StandardCharsets.UTF_8));
        String json_send_sms = "{\"cust_code\":\"" + cust_code + "\",\"sp_code\":\"" + sp_code + "\",\"content\":\"" + content +
                "\",\"destMobiles\":\"" + destMobiles + "\",\"uid\":\"" + uid + "\",\"need_report\":\"" + need_report + "\",\"sign\":\"" + sign + "\"}";
        return post(url_send_sms,json_send_sms);

    }


    /**
     * 提交单条普通短信
     */
    public boolean sendVerifyCode(String phone, String valicode) {
        log.info("发送验证码to[" + phone + "]" + valicode);
        try {
            String response = sendCommSms(phone,//
                    valicode + "是您本次的验证码，请在1分钟内正确输入，请勿泄露此验证码。");//
            if(response == null){
                return false;
            }
            JSONObject jsonObject = JSONObject.parseObject(response);

            return jsonObject != null && jsonObject.get("status").equals("success");
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public SmsResultBean parseReportResponse(String response){
        JSONArray array = JSONObject.parseArray(response);
        if(array == null || array.isEmpty()){
            return new SmsResultBean(false,"");
        }
        JSONObject newReportMap = array.getJSONObject(0);
        if (newReportMap.get("report").equals("DELIVRD") || newReportMap.get("report_status").equals("SUCCESS")) {
            return new SmsResultBean(true,"");
        }else {
            return new SmsResultBean(false,"");

        }

    }

    public String sendPlanFailedNotify(String phone, String content){
        try {
            return sendCommSms(phone, content);
        }catch (Exception e){
            e.printStackTrace();
            return SmsResultBean.failtString(e.getMessage());
        }
    }

    public String getAgentSmsName() {
//        return "聚U生活";
        if (agentSmsName == null) {
            byte[] bs = Base64.decodeBase64(agentSmsNameBase64);
            agentSmsName = new String(bs, StandardCharsets.UTF_8);
        }
        return agentSmsName;
    }


    /**
     * 验证码校验服务
     *
     * @param dtoPhone
     * @param dtoCode
     * @return
     */
    public BaseResponse validateSmscode(String dtoPhone, String dtoCode) {
        // 验证redis中是否验证码一致
        String code = redisService.get(dtoPhone);
        if (StringUtils.isEmpty(code)) {
            throw new AppRuntimeException("验证码已失效！请重新获取！");
        } else if (!code.equals(dtoCode)) {
            throw new AppRuntimeException("验证码输入不正确！");
        } else {
            return new BaseResponse(MsgCodeEnum.SUCCESS, null);
        }
    }

    public static void main(String[] args) throws Exception {
        WlwxSmsService smsService = new WlwxSmsService();
        smsService.cust_code = "560564";
        smsService.cust_pwd = "4Z3LOXYJ7N";
        smsService.agentSmsNameBase64 = "RmVlbA==";
        smsService.agentSmsNameBase64 = "5pyq5p2l5peg57q/";
        smsService.sendCommSms("17688151290", "您好，您的验证码为635241");

//        smsService.getReport();
    }
}
